# include "FileNames.h"

void MakeLowerString(string& text)
{
  unsigned char ch;
  for (int i = 0; i < text.size(); i++)
  {
    ch = text[i];
    if ((ch >= 'A') && (ch <= 'Z'))
      text[i] += 32;
  }
}

void
SubstBackslash(string& s)
{
  string::iterator pBegin = s.begin(), pEnd = s.end();
  char slash, backslash;
  backslash = '\\';
  slash     = '/';
  while (pBegin != pEnd)
  {
    if (*pBegin == backslash)
      *pBegin = slash;
    pBegin++;
  }
}

bool EraseFileExtension(string& fileName, string* extension)
{
  bool found = false;
  string ext;
  if (extension == NULL)
    ext = ".";
  else
    ext = *extension;
  string lowerExt(ext);
  MakeLowerString(lowerExt);
  string lowerFileName(fileName);
  SubstBackslash(lowerFileName);
  MakeLowerString(lowerFileName);
  int pos = lowerFileName.rfind(lowerExt);
  if (pos != basic_string<char>::npos)
  {
    fileName.erase(pos);
    found = true;
  }
  return found;
}

bool HasFileExtension(string& fileName, string* extension)
{
  bool found = false;
  string ext;
  if (extension == NULL)
    ext = ".";
  else
    ext = *extension;
  string lowerExt(ext);
  MakeLowerString(lowerExt);
  string lowerFileName(fileName);
  SubstBackslash(lowerFileName);
  MakeLowerString(lowerFileName);
  int pos = lowerFileName.rfind(lowerExt);
  if (pos != basic_string<char>::npos)
  {
    found = true;
  }
  return found;
}

bool ComparePath(string& path1, string& path2)
{
  string s1(path1.c_str()), s2(path2.c_str());
  MakeLowerString(s1);
  MakeLowerString(s2);
  return (s1.compare(s2) == 0);
}

void WriteString(ostream& os, const string& s)
{
  if (s.empty())
    os << "xxx" << endl;
  else
    os << s.c_str() << endl;
}

void ReadString(istream& is, string& s)
{
  is >> s;
  if (s.compare("xxx") == 0)
    s = "";
}

